﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;

namespace JzSport.WebApp
{
    public class Global : System.Web.HttpApplication
    {
        public static Thread _thread;
        public static bool _isRunning = false;
        public static long _ticks = 0;
        public static EventWaitHandle _wait;

        protected void Application_Start(object sender, EventArgs e)
        {
            JizSport.Common.Logger.InitByLogDirectory(Server.MapPath("~/Logs/"));
            JzSport.Model.Configs.Init();

        }

        public static void StartActivityMonitorThread()
        {
            if (_thread == null)
            {
                _wait = new EventWaitHandle(false, EventResetMode.ManualReset);
                _thread = new Thread(Running);
                _isRunning = true;
                _thread.Start();
                JizSport.Common.Logger.DebugToTag("monitor thread", "线程开启！");
            }
        }

        public static void StopActivityMonitorThread()
        {
            if (_thread != null && _isRunning)
            {
                _isRunning = false;
                _wait.WaitOne();
                _thread = null;
                _wait = null;
                JizSport.Common.Logger.DebugToTag("monitor thread", "线程关闭！");
            }
        }

        private static void Running(object obj)
        {
            while (_isRunning)
            {
                if (DateTime.Now.Ticks - _ticks > TimeSpan.FromMinutes(5).Ticks)
                {
                    new JzSport.Model.ActivityService().UpdateActivityState();
                    _ticks = DateTime.Now.Ticks;
                    JizSport.Common.Logger.DebugToTag("monitor thread", "执行活动状态更新！");
                }
                else
                {
                    Thread.Sleep(1000);
                }
            }
            _wait.Set();
        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {

        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected void Application_Error(object sender, EventArgs e)
        {

        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {
            //_isRunning = false;
            //_wait.WaitOne();
            //_thread = null;
            //JizSport.Common.Logger.DebugToTag("monitor thread", "线程关闭！");
        }
    }

}